package com.spzx.cart.service.Impl;

import com.spzx.cart.api.domain.CartItem;

import com.spzx.cart.service.CartItemService;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.ProductSkuVO;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartItemServiceImpl implements CartItemService {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    RemoteProductService remoteProductService;

    @Override
    public boolean add2Cart(Long skuId, Integer skuNum) {
        Long userId = SecurityUtils.getUserId();// 登录才能使用购物车 并且登录后会带jwt 然后解析
        BoundHashOperations cart = getCart();

        CartItem cartItem;
        // 获取购物车中 本次新增sku对应的购物项
        Object obj = cart.get(skuId.toString());
        if (obj == null) {
            if (cart.size() + 1 >= 5) {
                throw new ServiceException("添加商品的种类不得超过4种！");
            }
            cartItem = new CartItem();
            cartItem.setSkuId(skuId);
            cartItem.setSkuNum(skuNum);
            cartItem.setCreateTime(new Date());
            cartItem.setUpdateTime(new Date());
            cartItem.setUserId(userId);
            R<ProductSkuVO> skuVOR = remoteProductService.getSkuDetails(skuId);
            if (R.SUCCESS != skuVOR.getCode()) { // 如果查询的结果不等于它
                throw new ServiceException("商品数据不存在！");
            }
            ProductSkuVO skuVO = skuVOR.getData();
            cartItem.setCartPrice(skuVO.getSkuPrice().getSalePrice());
            cartItem.setThumbImg(skuVO.getProductSku().getThumbImg());
            cartItem.setSkuPrice(skuVO.getSkuPrice().getSalePrice());
            cartItem.setSkuName(skuVO.getProductSku().getSkuName());//需要根据skuId查询sku详情数据
        } else {
            //2、如果购物车中已存在该商品，修改该购物项的数量
            cartItem = (CartItem) obj;
            cartItem.setSkuNum(skuNum + cartItem.getSkuNum());
            cartItem.setUpdateTime(new Date());

        }
        //使用redis保存购物项数据
        // 购物车数据缓存在redis中，java代码加载修改后 必须重新设置回redis

        cart.put(skuId.toString(), cartItem);


        return true;
    }


    private BoundHashOperations getCart() {
        //0、获取用户的购物车
        BoundHashOperations cart = redisTemplate.boundHashOps("spzx:cart:" + SecurityUtils.getUserId());
        return cart;
    }


    @Override
    public List<CartItem> cartList() {
        BoundHashOperations cart = getCart();
        // 获取购物成功中的购物项集合
        List<CartItem> cartItems = cart.values();

        cartItems.forEach((cartItem) -> {
            R<ProductSkuVO> skuVOR = remoteProductService.getSkuDetails(cartItem.getSkuId());
            if (R.SUCCESS != skuVOR.getCode()) {
                throw new ServiceException("商品数据不存在！");
            }
            cartItem.setSkuPrice(skuVOR.getData().getSkuPrice().getSalePrice());
            // 将修改后的cartItem 同步到Redis中
            cart.put(cartItem.getSkuId().toString(),cartItem );
        });

        return cartItems;
    }

    @Override
    public boolean deleteCart(Long skuId) {
        BoundHashOperations cart = getCart();


        return cart.delete(skuId.toString()) > 0;
    }

    @Override
    public boolean checkCart(Long skuId, Integer status) {
        BoundHashOperations cart = getCart();

        Object obj = cart.get(skuId.toString());
        if (obj == null) {
            throw new ServiceException("数据不存在！");
        }
        CartItem cartItem = (CartItem) obj;
        cartItem.setIsChecked(status);
        cart.put(skuId.toString(), cartItem);
        return true;
    }

    @Override
    public boolean allCheckCart(Integer status) {
        BoundHashOperations cart = getCart();

        cart.entries().forEach((skuId, cartItem) -> {
            CartItem ci = (CartItem) cartItem;
            ci.setIsChecked(status);
            cart.put(skuId.toString(), ci);


        });


        return true;
    }

    @Override
    public boolean clearCart() {
        redisTemplate.delete("spzx:cart:" + SecurityUtils.getUserId());
        return true;
    }

    @Override
    public List<CartItem> getCheckedCartItems() {
        BoundHashOperations cart = getCart();
        List<CartItem> cartItems = cart.values();

        return cartItems.stream()
                .filter(cartItem -> cartItem.getIsChecked().longValue() == 1l)
                .collect(Collectors.toList());
    }

    @Override
    public boolean delCheckedCartItems() {

        BoundHashOperations<String,String,CartItem> cart = getCart();
        cart.entries().forEach((skuIdStr , cartItem)->{
            if(cartItem.getIsChecked().intValue() == 1){
                cart.delete(skuIdStr);
            }
        });
        return true;
    }


}



